<!-- 上传组件 -->
<template>
	<view class="me-upload" :class="{disabled}" @click.stop="uploadFile">
		<text>{{tip}}</text>
		<template v-if="preview&&value&&!loading">
			<image class="preview" :src="value" mode="scaleToFill"></image>
			<text class="icon-close uni-icons-closeempty" @click.stop="del"></text>
		</template>
	</view>
</template>

<script>
	import {showToast} from '../../common/util.js';
	export default {
		data() {
			return {
				percent: 0
			}
		},
		props:{
			value: String, // 图片地址
			disabled: Boolean, // 是否禁用
			preview: { // 是否预览
				type: Boolean,
				default: true
			}
		},
		computed:{
			loading(){
				return this.percent > 0 && this.percent < 100
			},
			tip(){
				return this.loading ? ("上传中 "+this.percent+"%") : "上传"
			}
		},
		methods: {
			uploadFile() {
				if(this.disabled) return;
				// 选择文件
				uni.chooseImage({
					count: 1,
					success: res=>{
						if (res.tempFilePaths.length > 0) {
							let filePath = res.tempFilePaths[0]
							let fileInfo = res.tempFiles[0]
							console.log("选择文件: ", res);
							let fileType = fileInfo.name.substr(fileInfo.name.lastIndexOf('.')) // 拓展名
							let fileName = Date.now() + Math.random().toString(36).substr(2,16) + fileType // 必须带拓展名,否则上传失败
							console.log("上传文件名: " + fileName);
							//进行上传操作
							uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: fileName,
								onUploadProgress: e => {
									this.percent = Math.round((e.loaded * 100) / e.total)
									console.log("上传进度: " + this.percent);
								},
								success: res=>{
									console.log("上传成功: ", res);
									this.$emit("input", res.fileID)
									showToast("上传成功")
								},
								fail: e=>{
									console.log("上传失败: ", e);
									showToast('上传失败: ' + JSON.stringify(e))
								}
							})
						}
					}
				});
			},
			del(){
				this.$emit("input", "")
			}
		}
	}
</script>

<style lang="scss">
	.me-upload {
		position: relative;
		width: 100px;
		height: 50px;
		line-height: 50px;
		display: inline-block;
		vertical-align: middle;
		text-align: center;
		background: $uni-color-primary;
		color: #fff;
		cursor: pointer;
		&.disabled{
			background: #C3C3C3;
		}
		
		.preview{
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}
		
		.icon-close{
			position: absolute;
			top: -10px;
			right: -10px;
			width: 20px;
			height: 20px;
			line-height: 20px;
			border-radius: 50%;
			font-size: 14px;
			text-align: center;
			background-color: #ff4d4f;
			color: #fff;
		}
	}
</style>
